#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#include "census.h"
#include "censusmaster.h"

struct Socket socketSendReceive;
void (*slaveFoundCallback)(struct Address *);
pthread_t threadReceiveAnswers;
int continueCensus;

void masterCensusSendRequests()
{
	struct Packet request;
	request.size = sprintf(request.buffer, CENSUS_REQUEST);
	
	while(continueCensus)
	{
		if(0 == broadcastPacket(&socketSendReceive, &request, CENSUS_PORT))
		{
			// Packet was broadcasted
		}
		sleep(1);
	}
}

void masterCensusReceiveAnswers()
{
	if(0 == createSocketUDP(&socketSendReceive, 0))
	{
		setSocketNonBlocking(&socketSendReceive);
		
		if(0 == bindSocket(&socketSendReceive))
		{
			pthread_t threadSendRequests;
			pthread_create(&threadSendRequests, 0, (void *)&masterCensusSendRequests, 0);
			
			struct Packet packet;
			struct Address address;
			
			while(continueCensus)
			{
				if(0 == receivePacket(&socketSendReceive, &packet, &address))
				{
					if(isAnswer(packet.buffer, packet.size))
					{
						slaveFoundCallback(&address);
					}
				}
				
				usleep(50);
			}
		}
	}
}

void startCensusMaster(void (*slaveFound)(struct Address *))
{
	slaveFoundCallback = slaveFound;
	
	continueCensus = 1;
	
	pthread_create(&threadReceiveAnswers, 0, (void *)&masterCensusReceiveAnswers, 0);
}

void stopCensusMaster()
{
	continueCensus = 0;
}
